package cn.wolfcode.p2p.business.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.wolfcode.p2p.base.domain.Account;
import cn.wolfcode.p2p.base.service.IAccountService;
import cn.wolfcode.p2p.base.util.UserContext;
import cn.wolfcode.p2p.business.domain.RechargeOffline;
import cn.wolfcode.p2p.business.mapper.RechargeOfflineMapper;
import cn.wolfcode.p2p.business.query.RechargeOfflineQueryObject;
import cn.wolfcode.p2p.business.service.IAccountFlowService;
import cn.wolfcode.p2p.business.service.IRechargeOfflineService;

@Service
@Transactional
public class RechargeOfflineServiceImpl implements IRechargeOfflineService {

	@Autowired
	private RechargeOfflineMapper rechargeMapper;

	@Autowired
	private IAccountService accountService;

	@Autowired
	private IAccountFlowService flowService;

	@Override
	public PageInfo query(RechargeOfflineQueryObject qo) {
		PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
		List<RechargeOffline> list = this.rechargeMapper.queryData(qo);
		return new PageInfo<>(list);
	}

	@Override
	public void apply(RechargeOffline to) {
		RechargeOffline ro = new RechargeOffline();
		ro.setAmount(to.getAmount());
		ro.setApplier(UserContext.getCurrent());
		ro.setApplyTime(new Date());
		ro.setBankInfo(to.getBankInfo());
		ro.setNote(to.getNote());
		ro.setRechargeDate(to.getRechargeDate());
		ro.setState(RechargeOffline.STATE_NORMAL);
		ro.setTradeCode(to.getTradeCode());
		this.rechargeMapper.insert(ro);
	}

	@Override
	public void audit(Long id, String remark, int state) {
		RechargeOffline ro = this.rechargeMapper.selectByPrimaryKey(id);
		// 判断是否处于待审核状态
		if (ro != null && ro.getState() == RechargeOffline.STATE_NORMAL) {
			// 设置相关审核属性
			ro.setAuditor(UserContext.getCurrent());
			ro.setAuditTime(new Date());
			ro.setState(state);
			ro.setRemark(remark);
			// 如果审核通过
			if (state == RechargeOffline.STATE_PASS) {
				// 1,用户可用余额增加
				Account account = this.accountService.get(ro.getApplier().getId());
				account.setUsableAmount(account.getUsableAmount().add(ro.getAmount()));
				// 2,创建一条账户流水信息
				this.flowService.createRechargeOfflineFlow(account, ro);
				this.accountService.update(account);
			}
			this.rechargeMapper.updateByPrimaryKey(ro);
		}
	}

}
